<?php

namespace App\Http\Controllers\Index;

use Style, DB, Config;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\News\NewsImgExist;
use App\Models\News\News;
use App\Models\News\NewsCategory;

class NewsController extends CommonController{

    /**
     * 资讯
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request){
        $request->only('id', 'search', 'page', 'class');
        $request->flash();
        empty($request->class) ? '' : $request->class = $request->class;
        //推荐
        $NewsImgExist = NewsImgExist::where('img_state', 1)->whereHas('imgWithNews', function($query) use ($request){
            $query->where('recommend', 1);
            if(!empty($request->class)){
                $query->where('category', $request->class);
            }
        })->with(
            ["imgWithNews" => function($query){
                $query->select('id', 'title', 'editorValue');
            }]
        )->groupBy('news_id')->orderBy('created_at', 'desc')->take(7)->get();

        //截取第一张图片
        foreach($NewsImgExist as $k => $v){
            if(preg_match_all('/<img(.*)?\s*src=\"(.*)\"(.*)\/>/Usi', $v->imgWithNews->editorValue, $arr)){
                $v->imgUrl = $arr[2][0];//取出第一张
            }else{
                $haveImg = 0;
            }
            $recommendId[$k] = $v->imgWithNews->id;
        }
        //最新资讯
        if(empty($recommendId) || count($recommendId) < 0){
            $recommendId = [];
        }
        $latelyNews = News::select('id', 'title', 'editorValue', 'style', 'readnum', 'updated_at')
            ->where(function($query) use ($request){
                if(!empty($request->class)){
                    $query->where('category', $request->class);
                }
                if(!empty($request->search)){
                    $query->where('title', 'like', '%' . $request->search . '%');
                }
            })
            ->where(function($query) use ($recommendId){
                if(count($recommendId) >= 7){
                    $query->whereNotIn('id', $recommendId);
                }
            })
            ->orderBy('updated_at', 'desc')->paginate(8);

        foreach($latelyNews as $k => $v){
            //有图片显示，无显示文本
            if(preg_match_all('/<img(.*)?\s*src=\"(.*)\"(.*)\/>/Usi', $v->editorValue, $arr)){
                $v->imgUrl = $arr[2][0];//取出第一张
                $v->content = msubstr(strip_tags($v->editorValue), 0, 68);
            }else{
                $v->content = msubstr(strip_tags($v->editorValue), 0, 100);
            }
            $v->updated_at = substr($v->updated_at, 0, 10);
        }
        //讯息分类
        $firstClass = NewsCategory::select('id')->where('new_sign', 'news')->first();
        if(!empty($firstClass)){
            $secondClass = NewsCategory::where('pid', $firstClass->id)->where('level', 1)->get();
        }else{
            $secondClass = (object)array();;
        }
        //图标地址
        $categoryImg = [
            0 => '/default/images/index/nwes01.png',
            1 => '/default/images/index/nwes02.png',
            2 => '/default/images/index/nwes03.png',
            3 => '/default/images/index/nwes04.png',
            4 => '/default/images/index/nwes05.png',
            5 => '/default/images/index/nwes06.png',
            6 => '/default/images/index/nwes07.png',
            7 => '/default/images/index/nwes08.png'
        ];
        if(!empty($secondClass) && count($secondClass) > 0){
            foreach($secondClass as $k => $v){
                //计算前十的阅读总合
                $readnum = DB::table('news')
                    ->select(DB::raw('sum(readnum) as allcount'))
                    ->where('category', '=', $v->id)
                    ->orderBy('readnum', 'desc')
                    ->take(10)
                    ->first();
                $v->count = $readnum->allcount;
                $v->img = $categoryImg[$k];
                if($v->id == $request->class){
                    $title = $v->defectsname;
                }
            }
        }
        if(empty($title)){
            $title = "最新资讯";
        }
        //热门文章+这个月阅读量最高的文章
        $mon = date("Y-m-d H:i:s", strtotime(' -1 month', time()));
        //热点新闻第一张带图
        $hotNewsWithPic = News::select('id', 'title', 'editorValue')->whereBetween('updated_at', [$mon, date("Y-m-d H:i:s", time())])
            ->whereHas('hotNewsWithPic', function($query){
                $query->where('img_state', 1);
            })
            ->with(["hotNewsWithPic" => function($query){
                $query->select('img_state');
            }])
            ->orderBy('readnum', 'desc')->first();

        if(!empty($hotNewsWithPic->editorValue)){
            if(preg_match_all('/<img(.*)?\s*src=\"(.*)\"(.*)\/>/Usi', $hotNewsWithPic->editorValue, $arr)){
                $hotNewsWithPic->imgUrl = $arr[2][0];//取出第一张
            }
        }
        $hotNews = News::select('id', 'title')->whereBetween('updated_at', [$mon, date('Y-m-d H:i:s')])
            ->orderBy('readnum', 'desc')
            ->take(9)->get();

        //分页链接
        if(!empty($request->class) and empty($request->search)){
            $pageStr = ['class' => $request->class];
        }elseif(empty($request->class) and !empty($request->search)){
            $pageStr = ['search' => $request->search];
        }elseif(!empty($request->class) and !empty($request->search)){
            $pageStr = ['class' => $request->class, 'search' => $request->search];
        }else{
            $pageStr = [];
        }
        return Style::view("index.news", compact('NewsImgExist', 'latelyNews', 'secondClass', 'hotNewsWithPic',
            'hotNews', 'pageStr', 'title'));
    }

    public function getImgUrl($str){
        preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i', $str, $match);
        $imgUrl = '';
        foreach($match as $v){
            if(!empty($match[1])){
                $imgUrl = $match[1];
                break;
            }
        }
        return $imgUrl;
    }
}